package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hy.corecode.idgen.WFGIdGenerator;
import io.xxx.xbutler.data.RobotLoginMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.RobotLogin;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 登录二维码回调接口
 * <p>
 * 通过relationSerialNo查询对应的登录二维码，这个二维码的有效期较短，数据可以及时清理。
 * <pre>
 * {
 *     "Data": {
 *         "nLogType": 0,
 *         "vcScanCodeUrl": "http://kfpt.oss-cn-hangzhou.aliyuncs.com/pc/QrCode/2025012510/acc5e5e6a84c42c69d2ea06100f7b98c.jpeg",
 *         "vcRelationSerialNo": ""
 *     },
 *     "nType": 1001,
 *     "nResult": 1,
 *     "vcResult": "Success",
 *     "nTimeStamp": 1737771122247,
 *     "vcSerialNo": "20250125101154524711116505156",
 *     "vcRobotWxId": "wxid_kultbellcta622",
 *     "vcMerchantNo": "202407150008480",
 *     "vcRobotSerialNo": "7155800509D08EAFBB39A2DCE845347E"
 * }
 * </pre>
 */
@Slf4j
@Component
public class _1001Handler implements CallbackHandler {

    @Resource
    private WFGIdGenerator idGenerator;

    @Resource
    private RobotLoginMapper robotLoginMapper;

    @Override
    public String name() {
        return "登录二维码回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 1001;
    }

    @Override
    public void handle(Callback callback) {
        LambdaQueryWrapper<RobotLogin> wrapper = new LambdaQueryWrapper<RobotLogin>()
                .eq(RobotLogin::getSerialNo, callback.getSerialNo());
        boolean exists = robotLoginMapper.exists(wrapper);
        if (!exists) {
            JSONObject data = (JSONObject) callback.getData();
            RobotLogin login = new RobotLogin()
                    .setId(idGenerator.next())
                    .setSerialNo(callback.getSerialNo())
                    .setRobotId(callback.getRobotId())
                    .setRobotSerialNo(callback.getRobotSerialNo())
                    .setScanCode(data.getString("vcScanCodeUrl"))
                    .setRelationSerialNo(data.getString("vcRelationSerialNo"))
                    .setLogType(data.getInteger("nLogType"))
                    .setCreatedTime(LocalDateTime.now());
            robotLoginMapper.insert(login);
        }
    }
}
